package com.laijiale.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.laijiale.constant.ML;
import com.laijiale.dto.*;
import com.laijiale.entity.Course;
import com.laijiale.entity.User;
import com.laijiale.exception.ServiceException;
import com.laijiale.mapper.EpisodeMapper;
import com.laijiale.mapper.SeasonMapper;
import com.laijiale.result.Result;
import com.laijiale.until.MinioUtil;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.relation.RelationManager;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.laijiale.entity.Course;
import com.laijiale.mapper.CourseMapper;
import com.laijiale.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import vo.CourseSimpleListVO;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

import static com.laijiale.entity.table.CourseTableDef.COURSE;
import static com.laijiale.entity.table.CourseTableDef.COURSE;
import static com.laijiale.entity.table.EpisodeTableDef.EPISODE;
import static com.laijiale.entity.table.SeasonTableDef.SEASON;

/**
 * 课程表 服务层实现。
 *
 * @author laijiale
 * @since 2024-12-22
 */
@Service
@CacheConfig(cacheNames = "course")
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course>  implements CourseService{
    @Autowired
    private SeasonMapper seasonMapper;
    @Autowired
    private EpisodeMapper episodeMapper;


    @CacheEvict(allEntries = true)
    @Override
    public boolean insert(CourseInsertDTO dto) {
        //标题查重
        if(QueryChain.of(mapper).where(COURSE.TITLE.eq(dto.getTitle())).exists()){
            throw new ServiceException("课程标题已存在") ;

        }
        //组装entity实体类
          Course course= BeanUtil.copyProperties(dto,Course.class);
        course.setSummary(ML.Course.DEFAULT_SUMMARY);
        course.setCover(ML.Course.DEFAULT_COVER);

        course.setCreated(LocalDateTime.now());
        course.setUpdated(LocalDateTime.now());
        return mapper.insert(course)>0;

    }

    @Cacheable(key = "#p0",condition = "#p0 !=null",unless = "#result ==null")
    @Override
    public Course select(Long id) {
        RelationManager.addQueryRelations("category","seasons","episodes");
        return mapper.selectOneWithRelationsById(id);
    }
    @Cacheable(key = "#root.methodName",
            unless = "#result == null"
    )
    @Override
    public List<CourseSimpleListVO> simpleList() {
        List<CourseSimpleListVO> courseSimpleListVOS=QueryChain.of(mapper).listAs(CourseSimpleListVO.class);
        return courseSimpleListVOS;
    }

    @Cacheable(key = "#root.methodName + ':' + #p0.toString()",
            condition ="#p0 != null",
            unless = "#result == null")
    @Override
    public Page<Course> page(CoursePageDTO dto) {
        RelationManager.addQueryRelations("category","seasons","episodes");
        QueryChain<Course> queryChain = QueryChain.of(mapper)
                .orderBy(COURSE.IDX.asc(), COURSE.ID.desc());

        // title 条件
        String title = dto.getTitle();
        if(ObjectUtil.isNotNull(title)) {
            queryChain.where(COURSE.TITLE.like(title));
        }
        //categoryId条件
        Long categoryId =dto.getFkCategoryId();
        if (ObjectUtil.isNotNull(categoryId)){
            queryChain.where(COURSE.FK_CATEGORY_ID.eq(categoryId));
        }
        return queryChain.withRelations().page(new Page<>(dto.getPageNum(), dto.getPageSize()));
    }


    @CacheEvict(allEntries = true)
    @Override
    public boolean update(CourseUpdateDTO dto) {

        // 标题查重
        if (QueryChain.of(mapper).
                where(COURSE.TITLE.eq(dto.getTitle()))
                .and(COURSE.ID.ne(dto.getId()))
                .exists()) {
            throw new ServiceException("课程标题已存在");
        }

        // 组装 entity 实体类
        Course course = BeanUtil.copyProperties(dto, Course.class);
        // 设置 entity 默认值
        course.setUpdated(LocalDateTime.now());
        return UpdateChain.of(course).where(COURSE.ID.eq(course.getId())).update();
    }
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean delete(Long id) {
        List<Long> seasonIds =QueryChain.of(seasonMapper).select(SEASON.ID).where(SEASON.FK_COURSE_ID.eq(id))
                .objListAs(Long.class);
        //存在季记录，批删
        this.clearSeasonAndEpisode(seasonIds);
        return mapper.deleteById(id) > 0;

    }

    private void clearSeasonAndEpisode(List<Long> seasonIds) {
        if (ObjectUtil.isNotEmpty(seasonIds)){
            if (seasonMapper.deleteBatchByIds(seasonIds)<=0){
                throw new ServiceException("季次删除失败");
            }
        }
    List<Long> episodeIds =episodeMapper.selectObjectListByQueryAs(QueryWrapper.create().select(EPISODE.ID)
            .where(EPISODE.FK_SEASON_ID.in(seasonIds)),Long.class);
        //存在集批删
        if(ObjectUtil.isNotEmpty(episodeIds)){
            if (episodeMapper.deleteBatchByIds(episodeIds)<=0){
                throw new ServiceException("集次删除失败");
            }
        }

    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteBatch(List<Long> ids) {
        List<Long> seasonIds =QueryChain.of(seasonMapper).select(SEASON.ID).where(SEASON.FK_COURSE_ID.in(ids))
                .objListAs(Long.class);
        this.clearSeasonAndEpisode(seasonIds);
        return mapper.deleteBatchByIds(ids) > 0;
     }



    @Override
    @CacheEvict(allEntries = true)
    public Result<String> uploadSummary(MultipartFile summaryFile, Long id) {
        //按主键查询用户记录
        Course course = mapper.selectOneById(id);
        if (ObjectUtil.isNull(course)) {
            throw new ServiceException("课程不存在");
        }
        //备份旧头像
        String oldSummary = course.getSummary();
        //重新生成文件名
        String filename = MinioUtil.randomFilename(summaryFile);
        //根据用户主键修改用户头像
        course.setSummary(filename);
        if (mapper.update(course) <= 0) {
            throw new ServiceException("摘要更新失败：DB操作异常");
        }
        try {
            //从MinIO中删除旧头像：默认头像不删除
            if (!ML.Course.DEFAULT_SUMMARY.contains(oldSummary)) {
                MinioUtil.delete(oldSummary, ML.Minio.COURSE_SUMMARY_DIR, ML.Minio.BUCKET_NAME);
                //向MinIO中上传新头像
                MinioUtil.upload(summaryFile, filename, ML.Minio.COURSE_SUMMARY_DIR, ML.Minio.BUCKET_NAME);
            }
        } catch (Exception e) {
            throw new ServiceException("摘要更新失败：MinIo操作异常");
        }
        //返回文件名
        return new Result<>(filename);
    }

    @Override
    @CacheEvict(allEntries = true)
    public Result<String> uploadCover(MultipartFile coverFile, Long id) {
        //按主键查询用户记录
        Course course = mapper.selectOneById(id);
        if (ObjectUtil.isNull(course)) {
            throw new ServiceException("课程不存在");
        }
        //备份旧头像
        String oldCover = course.getCover();
        //重新生成文件名
        String filename = MinioUtil.randomFilename(coverFile);
        //根据用户主键修改用户头像
        course.setSummary(filename);
        if (mapper.update(course) <= 0) {
            throw new ServiceException("摘要更新失败：DB操作异常");
        }
        try {
            //从MinIO中删除旧头像：默认头像不删除
            if (!ML.Course.DEFAULT_COVER.contains(oldCover)) {
                MinioUtil.delete(oldCover, ML.Minio.COURSE_COVER_DIR, ML.Minio.BUCKET_NAME);
                //向MinIO中上传新头像
                MinioUtil.upload(coverFile, filename, ML.Minio.COURSE_COVER_DIR, ML.Minio.BUCKET_NAME);
            }
        } catch (Exception e) {
            throw new ServiceException("封面更新失败：MinIo操作异常");
        }
        //返回文件名
        return new Result<>(filename);
    }



    }

